package com.zhuiYun.project.api.userAddress.service.impl;

import com.zhuiYun.project.api.shArea.entiy.ShArea;
import com.zhuiYun.project.api.userAddress.entiy.UserAddress;
import com.zhuiYun.project.api.userAddress.mapper.UserAddressMapper;
import com.zhuiYun.project.api.userAddress.model.UserAddressModel;
import com.zhuiYun.project.api.userAddress.service.UserAddressService;
import com.zhuiYun.project.common.errorCode.CommonException;
import com.zhuiYun.project.common.errorCode.EmErrorCode;
import com.zhuiYun.project.common.response.CommonResult;
import com.zhuiYun.project.util.BeanUtils;
import com.zhuiYun.project.util.DateTimeUtils;
import com.zhuiYun.project.util.ObjectUtils;
import com.zhuiYun.project.util.pageUtil.MybatisPageHelper;
import com.zhuiYun.project.util.pageUtil.PageRequest;
import com.zhuiYun.project.util.pageUtil.PageResult;
import com.zhuiYun.project.util.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @ClassName UserAddressServiceImpl
 * @Description 收货地址管理
 * @Author 胡亮
 * @Date 2023/04/04 上午 10:11
 **/
@Service
public class UserAddressServiceImpl implements UserAddressService {

    @Autowired
    UserAddressMapper userAddressMapper;

    /**
    * @Author 胡亮
    * @Description 新增收货地址
    * @Date 2023/04/04 上午 10:28
    * @Return [com.zhuiYun.project.api.userAddress.model.UserAddressModel]
    */
    @Override
    public CommonResult saveAddress(UserAddressModel userAddressModel) throws CommonException {
        if(ValidatorUtil.ValidationObject(userAddressModel)){
            UserAddress address = new UserAddress();
            // userAddressModel 对象拷贝成 address
            BeanUtils.copy(userAddressModel, address);
            //查找是否有已存在的收货地址
            Example example = new Example(UserAddress.class);
            Example.Criteria criteria = example.createCriteria();
            //搜索条件userId
            criteria.andEqualTo("userId", address.getUserId());
            List<UserAddress> list = userAddressMapper.selectByExample(example);
            //如果没有收货地址设置为默认地址，有收货地址设置为普通地址
            if(ObjectUtils.isNotEmpty(list)){
                //获取当前时间
                Date date = new Date();
                //创建时间赋值
                address.setAddressCreateTime(date);
                //获得新增结果
                int i = userAddressMapper.insert(address);
                if(i>0){
                    return CommonResult.ok(EmErrorCode.SAVE_OK);
                }else{
                    return CommonResult.ok(EmErrorCode.SAVE_ERROR);
                }
            }else {
                //获取当前时间
                Date date = new Date();
                //创建时间赋值
                address.setAddressCreateTime(date);
                //赋值为默认地址
                address.setAddressFlag(1);
                //获得新增结果
                int i = userAddressMapper.insert(address);
                if(i>0){
                    return CommonResult.ok(EmErrorCode.SAVE_OK);
                }else{
                    return CommonResult.ok(EmErrorCode.SAVE_ERROR);
                }
            }
        }else {
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }

    /**
    * @Author 胡亮
    * @Description 分页查询
    * @Date 2023/04/04 下午 08:39
    * @Return [com.zhuiYun.project.util.pageUtil.PageRequest]
    */
    @Override
    public CommonResult getUserByPage(PageRequest pageRequest,Integer id) throws CommonException{
        Example example = new Example(UserAddress.class);
        //查找当前用户的收货地址
        Example.Criteria criteria = example.createCriteria();
        //搜索条件userId
        criteria.andEqualTo("userId",id);
        //排序条件address_flag（1为默认地址）
        example.setOrderByClause("address_flag desc");
        if(ObjectUtils.isNotEmpty(id)){
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        //查询
        List<UserAddress> addresses = userAddressMapper.selectByExample(example);
        for (UserAddress u:addresses) {
            //所在地区（汉字）赋值
            u.setLocation(u.getAddressLocationProvince()+"/"+u.getAddressLocationCity()+"/"+u.getAddressLocationCounty());
            //所在地区（id）赋值
            Integer[] locationId= new Integer[3];
            locationId[0]= Integer.valueOf(u.getAddressLocationProvinceId());
            locationId[1]= Integer.valueOf(u.getAddressLocationCityId());
            locationId[2]= Integer.valueOf(u.getAddressLocationCountyId());
            u.setLocationId(locationId);
        }
        PageResult pageResult = MybatisPageHelper.getPageResult(addresses);
        //返回结果
        return CommonResult.ok(pageResult);
        }else{
            throw new CommonException(EmErrorCode.ID_NULL);
        }
    }

    /**
    * @Author 胡亮
    * @Description 收货地址删除
    * @Date 2023/04/05 上午 10:25
    * @Return [java.lang.Integer]
    */
    @Override
    public CommonResult delAddressById(Integer id) throws CommonException{
        // 判断是否id为空
        if(ObjectUtils.isNotEmpty(id)){
            UserAddress userAddress = userAddressMapper.selectByPrimaryKey(id);
            if (ObjectUtils.isNotEmpty(userAddress)) {
                if(userAddress.getAddressFlag()==1){
                    Integer userId = userAddress.getUserId();
                    int i = userAddressMapper.deleteByPrimaryKey(id);
                    // 判断是否操作成功
                    if(i>0){
                        //查找是否有剩余的收货地址
                        Example example = new Example(UserAddress.class);
                        Example.Criteria criteria = example.createCriteria();
                        //条件userId
                        criteria.andEqualTo("userId", userId);
                        //排序条件创建时间（降序 最新地址）
                        example.setOrderByClause("address_create_time desc");
                        //搜索剩余的收货地址
                        List<UserAddress> list = userAddressMapper.selectByExample(example);
                        //剩余的收货地址不为空
                        if(ObjectUtils.isNotEmpty(list)){
                            //获取剩余的收货地址中最新的
                            userAddress = list.get(0);
                            //设置为默认地址
                            userAddress.setAddressFlag(1);
                            userAddressMapper.updateByPrimaryKeySelective(userAddress);
                        }
                        return CommonResult.ok(EmErrorCode.DELETE_OK);
                    }else{
                        return CommonResult.ok(EmErrorCode.DELETE_ERROR);
                    }
                }else {
                    int i = userAddressMapper.deleteByPrimaryKey(id);
                    // 判断是否操作成功
                    if(i>0){
                        return CommonResult.ok(EmErrorCode.DELETE_OK);
                    }else{
                        return CommonResult.ok(EmErrorCode.DELETE_ERROR);
                    }
                }
            }else {
                return CommonResult.ok(EmErrorCode.DELETE_ERROR);
            }
        }else{
            throw new CommonException(EmErrorCode.ID_NULL);
        }
    }

    /**
    * @Author 胡亮
    * @Description 修改收货的修改方法
    * @Date 2023/04/05 上午 11:01
    * @Return [com.zhuiYun.project.api.userAddress.model.UserAddressModel]
    */
    @Override
    public CommonResult updateAddress(UserAddressModel userAddressModel) throws CommonException{
        //获取当前时间(String类型)
        String minute = DateTimeUtils.getMinute();
        //String类型时间转Date类型
        Date date = DateTimeUtils.stringConvertDate(minute);
        //修改时间赋值
        userAddressModel.setAddressUpdateTime(date);
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(userAddressModel)){
            UserAddress address = new UserAddress();
            // userAddressModel 对象拷贝成 address
            BeanUtils.copy(userAddressModel, address);
            int i = userAddressMapper.updateByPrimaryKeySelective(address);
            if(i>0){
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            }else{
                return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
            }
        }else{
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
    * @Author 胡亮
    * @Description 修改默认收货地址(默认地址唯一)
    * @Date 2023/04/05 下午 02:39
    * @Return [java.lang.Integer]
    */
    @Override
    public CommonResult updateAddressById(UserAddressModel userAddressModel) throws CommonException{
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(userAddressModel)) {
            UserAddress Address = new UserAddress();
            // userAddressModel 对象拷贝成 Address
            BeanUtils.copy(userAddressModel, Address);
            Address.setAddressFlag(1);
            //获取当前默认地址
            UserAddress address = new UserAddress();
            address.setAddressFlag(1);
            address.setUserId(Address.getUserId());
            UserAddress userAddress = userAddressMapper.selectOne(address);
            //判断当前默认地址是否存在
            if (ObjectUtils.isNotEmpty(userAddress)) {
                //如果存在取消其默认地址状态
                userAddress.setAddressFlag(0);
                userAddressMapper.updateByPrimaryKeySelective(userAddress);
                //设置最新默认地址
                int i = userAddressMapper.updateByPrimaryKeySelective(Address);
                //判断是否修改成功
                if (i > 0) {
                    return CommonResult.ok(EmErrorCode.UPDATE_OK);
                } else {
                    return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
                }
            }else {
                //如果不存在直接设置最新默认地址
                int i = userAddressMapper.updateByPrimaryKeySelective(Address);
                //判断是否修改成功
                if (i > 0) {
                    return CommonResult.ok(EmErrorCode.UPDATE_OK);
                } else {
                    return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
                }
            }
        }else {
            throw new CommonException(EmErrorCode.UPDATE_ERROR);
        }

    }

    /**
    * @Description 根据用户id获取收货地址
    * @Author lzy
    * @Date 2023/4/6 19:22
    * @Return com.zhuiYun.project.common.response.CommonResult
    * @param userId
    */
    @Override
    public CommonResult getAddressByUserId(Integer userId) {
        List<UserAddress> addressList = userAddressMapper.getAddressList(userId);
        return CommonResult.ok(addressList);
    }

    /**
     * @Author gpd
     * @Description  新增用户地址（uniapp新增用户地址）
     * @Date 2023-04-15 上午 11:05
     * @Return com.zhuiYun.project.common.response.CommonResult

     */
    @Override
    public Integer addUserAddress(UserAddress userAddress) {
        userAddress.setAddressCreateTime(new Date());
        return userAddressMapper.insertSelective(userAddress);
    }

    /**
     * @Author gpd
     * @Description 查询用户的所有收货地址
     * @Date 2023-04-15 上午 11:45
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param userId
     */
    @Override
    public List<UserAddress> getUserAllAddress(Integer userId) {
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(userId);
        return userAddressMapper.select(userAddress);
    }

    /**
     * @Author gpd
     * @Description 查询用户点击的地址详情
     * @Date 2023-04-15 下午 12:15
     * @Return com.zhuiYun.project.common.response.CommonResult
     * @param id
     */
    @Override
    public UserAddress getUserSelectAddress(Integer id) {
        UserAddress userAddress = new UserAddress();
        userAddress.setId(id);
        return userAddressMapper.selectOne(userAddress);
    }

    /**
     * @Author gpd
     * @Description 修改用户地址 （uniapp 修改地址）
     * @Date 2023-04-15 下午 12:27
     * @Return com.zhuiYun.project.common.response.CommonResult

     */
    @Override
    public Integer updateUserAddress(UserAddress userAddress) {
        return userAddressMapper.updateByPrimaryKeySelective(userAddress);
    }


}
